package com.iiitb.wtp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class URLConnect {

	String tag = "";

	public String getTag() {
		return tag;
	}

	public void setTag(String tag) {
		this.tag = tag;
	}

	public URLConnect(Map<String, String> urlList) {

		Parser ObjParse = new Parser();
		Map<String, String> list = new HashMap<String, String>();
		// for(int i=0; i<urlList.size(); i++){
		// Iterator iter = urlList.entrySet().iterator();
		for (int i = 0; i < 2; i++) {

			for (Map.Entry<String, String> entry : urlList.entrySet()) {
				// while(iter.hasNext()){
				String url = entry.getKey();
				
				try {
					HttpHost proxy = new HttpHost("192.168.3.254", 8080, "http");
					HttpClient client = new DefaultHttpClient();
					client.getParams().setParameter(
							ConnRoutePNames.DEFAULT_PROXY, proxy);
					HttpGet get = new HttpGet(url);

					HttpResponse response = client.execute(get);
					InputStreamReader is = new InputStreamReader(response
							.getEntity().getContent(), "UTF8");
					BufferedReader rd = new BufferedReader(is);

					String line;
					String sourceLine = null;

					while ((line = rd.readLine()) != null) {
						sourceLine = sourceLine + line;
					}
					if (entry.getValue().equals("")) {
						setTag(ObjParse.parseTag(sourceLine));
					}
					// Call the parser from here
					else {
						list.putAll(ObjParse.parse(sourceLine, url,
								entry.getValue(), urlList));
						// urlList.putAll(list);
					}

					rd.close();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			urlList.clear();
			urlList.putAll(list);
		}
	}
}